import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Viewer } from 'cesium'

interface CesiumViewer {
  loadCzmlData: (data: any) => Promise<boolean>
  destroy: () => void
}

export const useCesiumStore = defineStore('cesium', () => {
  const czmlData = ref<any>(null)
  const viewer = ref<CesiumViewer | null>(null)

  const addCzmlData = async (response: any) => {
    if (response.code !== 0) {
      return false
    }
    
    try {
      // 如果返回的是CZML字符串，直接使用
      if (typeof response.data === 'string' && response.data.trim().startsWith('[')) {
        czmlData.value = response.data
        if (viewer.value) {
          return await viewer.value.loadCzmlData(response.data)
        }
      }
      // 如果是JSON格式的CZML数据
      else if (typeof response.data === 'object') {
        czmlData.value = JSON.stringify(response.data)
        if (viewer.value) {
          return await viewer.value.loadCzmlData(response.data)
        }
      }
      return false
    } catch (error) {
      console.error('处理CZML数据失败:', error)
      return false
    }
  }

  const setViewer = (instance: CesiumViewer) => {
    viewer.value = instance
  }

  return {
    czmlData,
    viewer,
    addCzmlData,
    setViewer
  }
})
